package com.coder.widget.slidecard

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import kotlin.math.min

/**
 * 滑动卡片布局管理器
 * https://my.oschina.net/sfshine/blog/1604007
 *
 * @author yuhushuan
 * @date 2020/11/6 17:59
 */
class SlideCardLayoutManager() : RecyclerView.LayoutManager() {
    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    override fun onLayoutChildren(recycler: Recycler, state: RecyclerView.State?) {
        // ViewHolder 回收复用
        detachAndScrapAttachedViews(recycler)
        val itemCount = itemCount
        val displayCount = min(itemCount, CardConfig.MAX_DISPLAY_COUNT)


        // 从底层开始，上层覆盖显示
        for (i in displayCount - 1 downTo 0) {
            // 复用
            val view = recycler.getViewForPosition(i)
            addView(view)
            measureChildWithMargins(view, 0, 0)
            val widthSpace = width - getDecoratedMeasuredWidth(view)
            val heightSpace = height - getDecoratedMeasuredHeight(view)

            // 居中
            layoutDecoratedWithMargins(view, widthSpace / 2, heightSpace / 2,
                    widthSpace / 2 + getDecoratedMeasuredWidth(view),
                    heightSpace / 2 + getDecoratedMeasuredHeight(view))

            // i = 0 时，不缩放
            if (i > 0) {
                if (i < CardConfig.MAX_DISPLAY_COUNT - 1) {
                    view.translationY = CardConfig.TRANS_Y_GAP * i
                    view.scaleX = 1 - CardConfig.SCALE_GAP * i
                    view.scaleY = 1 - CardConfig.SCALE_GAP * i
                } else { // 最后一层，与上一层一致
                    view.translationY = CardConfig.TRANS_Y_GAP * (i - 1)
                    view.scaleX = 1 - CardConfig.SCALE_GAP * (i - 1)
                    view.scaleY = 1 - CardConfig.SCALE_GAP * (i - 1)
                }
            }
        }
    }
}